/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.common.bean.RoleBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.purpose.bean.SafetyMeetingBean;
import com.koron.purpose.mapper.SafetyMeetingMapper;
import com.koron.purpose.service.api.SafetyMeetingService;
import com.koron.purpose.utils.BusinessCode;
import com.koron.purpose.utils.PdfFileUtil;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
@SuppressWarnings("deprecation")
public class SafetyMeetingServiceImpl implements SafetyMeetingService {

    private final Logger logger = LoggerFactory.getLogger(SafetyMeetingServiceImpl.class);

    // 文件操作类
    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;

    @Autowired
    private PdfFileUtil pdfFileUtil;

    // 管理员 role 的code编码
    @Value("${app.managerRole}")
    private String managerRole;

    @Autowired
    private Util util;

    @Override
    public MessageBean<?> deleteSafetyMeeting(String id, StaffBean user) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            SafetyMeetingMapper mapper = factory.getMapper(SafetyMeetingMapper.class);
            SafetyMeetingBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该安全会议已失效，请刷新页面!");
                return msg;
            }
            // 如果当前人 为创建人，直接删除，否则判断该用户是否为管理员，如果为管理员，也可以进行删除
            if (user.getCode().equals(bean.getAddUser())) {
                mapper.deleteSafetyMeeting(id);
            } else {
                // 获取用户角色群组列表：1024查询对象为角色，512查询对象为群组。1024+512：角色+群组
                MessageBean rolesMsg = util.getRolesAndGroupsByStaff(user.getCode(), 1024);
                if (BusinessCode.SUCCESS.getCode() == rolesMsg.getCode()) {
                    Map map = (Map) rolesMsg.getData();
                    List<RoleBean> roleList = (List<RoleBean>) map.get("role");
                    if (roleList.stream().anyMatch(roleBean -> roleBean.getCode().equals(managerRole))) {
                        mapper.deleteSafetyMeeting(id);
                        return msg;
                    }
                }
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("创建人才有权删除!");
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> insert(SafetyMeetingBean bean, StaffBean user, MultipartFile[] files, String jobsTasksId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(bean.getMeetingName()) || StringUtils.isEmpty(bean.getMeetingTitle())
                || StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getCorpName())
                || bean.getMeetingTime() == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
//        if (StringUtils.isEmpty(bean.getMeetingName()) || StringUtils.isEmpty(bean.getMeetingTitle())
//                || StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getCorpName())
//                || StringUtils.isEmpty(bean.getManager()) || StringUtils.isEmpty(bean.getManagerName())
//                || StringUtils.isEmpty(bean.getMeetingUser()) || StringUtils.isEmpty(bean.getMeetingUserName())
//                || bean.getMeetingTime() == null || StringUtils.isEmpty(bean.getMeetingJoinUsers())) {
//            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
//            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
//            return msg;
//        }
        SessionFactory factory = new SessionFactory();
        try {
            SafetyMeetingMapper mapper = factory.getMapper(SafetyMeetingMapper.class);
            // 附件保存
            if (files == null) {
                bean.setMeetingRecord("");
            } else {
                JSONArray array = new JSONArray();
                JSONObject object;
                for (MultipartFile file : files) {
                    object = new JSONObject();
                    object.put("filename", file.getOriginalFilename());
                    object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
                    object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
                    array.add(object);
                }
                bean.setMeetingRecord(JSON.toJSONString(array));
            }
            Date date = new Date();
            bean.setAddTime(date);
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setUpdateTime(date);
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setId(DefaultIdGenerator.getInstance().generateLongId());
            // 新增安全会议
            mapper.insertSafetyMeeting(bean);
            // 判断 工作任务id 是否为空：如果不为空，则进行 会议工作信息变更
            if (!StringUtils.isEmpty(jobsTasksId)) {
                JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                // 根据 工作任务id 查询该条 工作任务记录
                JobsTasks jobsTasks = jobsTasksMapper.queryById(jobsTasksId);
                if (jobsTasks == null) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("该工作任务已失效，请刷新页面!");
                    return msg;
                }
                // 完成日期
                Date completedTime = new Date();
                // 任务状态：-1废弃，0待办，1完成，2延时完成，3执行中
                int state;
                if (jobsTasks.getEndTime() == null || jobsTasks.getEndTime().after(completedTime)) {
                    state = 1;
                } else {
                    state = 2;
                }
                // 流程状态：0草稿 1审批中 2审批通过
                int fstatusflag = 0;
                // 业务id
                String businessId = bean.getId();
                JobsTasks updateJob = new JobsTasks();
                updateJob.setId(jobsTasksId);
                updateJob.setState(state);
                updateJob.setFstatusflag(fstatusflag);
                updateJob.setCompletedTime(completedTime);
                updateJob.setBusinessId(businessId);
                if (jobsTasksMapper.completed(updateJob) != 1) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("该工作任务已失效，请刷新页面!");
                    return msg;
                }
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<SafetyMeetingBean> queryById(String id) {
        MessageBean<SafetyMeetingBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), SafetyMeetingBean.class);
        SessionFactory factory = new SessionFactory();
        try {
            SafetyMeetingMapper mapper = factory.getMapper(SafetyMeetingMapper.class);
            // 根据id 查询 安全会议
            SafetyMeetingBean bean = mapper.queryById(id);
            msg.setData(bean);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> updateSafetyMeeting(SafetyMeetingBean bean, StaffBean user, MultipartFile[] files, String jobsTasksId) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        if (user == null) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            SafetyMeetingMapper mapper = factory.getMapper(SafetyMeetingMapper.class);
            // 根据id 查询 安全会议
            SafetyMeetingBean safetyMeeting = mapper.queryById(bean.getId());
            if (safetyMeeting == null) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该安全会议已失效，请刷新页面!");
                factory.close(false);
                return msg;
            }
            if (!user.getCode().equals(safetyMeeting.getAddUser())) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("创建人才有权编辑!");
                factory.close(false);
                return msg;
            }
            bean.setUpdateTime(new Date());
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            mapper.updateSafetyMeeting(bean);
            // 修改 会议记录
            updateSafetyMeetRecord(bean.getId(), bean.getMeetingRecord(), files, mapper);
            // 判断 工作任务id 是否为空：如果不为空，则进行 会议工作信息变更
            if (!StringUtils.isEmpty(jobsTasksId)) {
                JobsTasksMapper jobsTasksMapper = factory.getMapper(JobsTasksMapper.class);
                // 根据 工作任务id 查询该条 工作任务记录
                JobsTasks jobsTasks = jobsTasksMapper.queryById(jobsTasksId);
                if (jobsTasks == null) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("该工作任务已失效，请刷新页面!");
                    return msg;
                }
                // 完成日期
                Date completedTime = new Date();
                // 任务状态：-1废弃，0待办，1完成，2延时完成，3执行中
                int state;
                if (jobsTasks.getEndTime() == null || jobsTasks.getEndTime().after(completedTime)) {
                    state = 1;
                } else {
                    state = 2;
                }
                // 流程状态：0草稿 1审批中 2审批通过
                int fstatusflag = 0;
                // 业务id
                String businessId = bean.getId();
                JobsTasks updateJob = new JobsTasks();
                updateJob.setId(jobsTasksId);
                updateJob.setState(state);
                updateJob.setFstatusflag(fstatusflag);
                updateJob.setCompletedTime(completedTime);
                updateJob.setBusinessId(businessId);
                if (jobsTasksMapper.completed(updateJob) != 1) {
                    factory.close(false);
                    msg.setCode(BusinessCode.EXCEPTION.getCode());
                    msg.setDescription("该工作任务已失效，请刷新页面!");
                    return msg;
                }
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<DataBean<Map>> querySafetyMeeting(String corpCode, String managerName, String meetingUserName,
                                                         String meetingTimeStart, String meetingTimeStop,
                                                         Integer page, Integer pageSize) {
        MessageBean<DataBean<Map>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            SafetyMeetingMapper mapper = factory.getMapper(SafetyMeetingMapper.class);
            DataBean<Map> dataBean = new DataBean<>();
            Map<String, Object> map = new HashMap<>();
            map.put("corpCode", corpCode);
            map.put("managerName", managerName);
            map.put("meetingUserName", meetingUserName);
            map.put("meetingTimeStart", meetingTimeStart);
            map.put("meetingTimeStop", meetingTimeStop);
            // 分页起始位置
            Integer pageStart = (page - 1) * pageSize;
            map.put("pageStart", pageStart);
            map.put("pageStop", pageSize);
            List<Map> list = mapper.querySafetyMeeting(map);
            dataBean.setList(list);
            // 总条数
            Integer totalNumber = mapper.countQuerySafetyMeeting(map);
            int num = totalNumber / pageSize;
            // 总页数
            Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询安全会议列表成功");
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> deleteFile(String fileUrl) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        fastDFSClientWrapper.deleteFile(fileUrl);
        return msg;
    }

    @Override
    public List<Map> querySafetyMeetings(String corpCode, String managerName, String meetingUserName,
                                         String meetingTimeStart, String meetingTimeStop) {
        Map<String, Object> map = new HashMap<>();
        map.put("corpCode", corpCode);
        map.put("managerName", managerName);
        map.put("meetingUserName", meetingUserName);
        map.put("meetingTimeStart", meetingTimeStart);
        map.put("meetingTimeStop", meetingTimeStop);
        List<Map> list = null;
        try (SessionFactory factory = new SessionFactory()) {
            SafetyMeetingMapper mapper = factory.getMapper(SafetyMeetingMapper.class);
            list = mapper.querySafetyMeeting(map);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return list;
    }

    /**
     * 判断map中的 key是否在list中存在
     *
     * @param map
     * @param list
     * @param key
     * @return
     */
    private boolean filter(Map<String, String> map, List<Map> list, String key) {
        String str = map.get(key);
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        if (list == null || list.size() == 0) {
            return false;
        }
        for (Map m : list) {
            if (str.equals(Optional.ofNullable(m.get(key)).get().toString())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 修改 会议记录
     *
     * @param id            安全会议id
     * @param meetingRecord 会议记录
     * @param files         文件
     * @return
     */
    private void updateSafetyMeetRecord(String id, String meetingRecord, MultipartFile[] files, SafetyMeetingMapper mapper) throws Exception {
        // 根据id 查询 安全会议
        SafetyMeetingBean safetyMeeting = mapper.queryById(id);
        if (safetyMeeting == null) {
            throw new Exception("该安全会议已失效!");
        }
        List<String> deleteFileUrls = new LinkedList<>();
        // 删除会议记录文件
        String record = safetyMeeting.getMeetingRecord();
        if (!StringUtils.isEmpty(record)) {
            List<Map> meetingRecords_old = JSON.parseArray(record, Map.class);
            List<Map> meetingRecords_new = null;
            if (!StringUtils.isEmpty(meetingRecord)) {
                meetingRecords_new = JSON.parseArray(meetingRecord, Map.class);
                for (Map map : meetingRecords_old) {
                    if (!filter(map, meetingRecords_new, "fileUrl")) {// 不存在:删除文件
                        deleteFileUrls.add(map.get("fileUrl").toString());
                        if (!StringUtils.isEmpty(Optional.ofNullable(map.get("pdfUrl")).orElse("").toString())) {
                            deleteFileUrls.add(map.get("pdfUrl").toString());
                        }
                    }
                }
            }
        }
        String recordStr = "";
        // 附件保存
        if (files != null) {
            JSONArray array;
            if (!StringUtils.isEmpty(meetingRecord)) {
                array = JSON.parseArray(meetingRecord);
            } else {
                array = new JSONArray();
            }
            JSONObject object;
            for (MultipartFile file : files) {
                object = new JSONObject();
                object.put("filename", file.getOriginalFilename());
                object.put("fileUrl", fastDFSClientWrapper.uploadFile(file));
                object.put("pdfUrl", pdfFileUtil.getPdfUrl(file, fastDFSClientWrapper));
                array.add(object);
            }
            recordStr = JSON.toJSONString(array);
            safetyMeeting.setMeetingRecord(recordStr);
        }
        int i = mapper.updateSafetyMeetingRecord(id, safetyMeeting.getMeetingRecord());
        if (i != 1) {
            throw new Exception("修改安全会议记录失败!");
        }
        // 删除文件服务器上的文件
        if (deleteFileUrls != null && deleteFileUrls.size() > 0) {
            for (String url : deleteFileUrls) {
                fastDFSClientWrapper.deleteFile(url);
            }
        }
    }
}
